"""
FileName：smart_auth_manager.py
Description：
Author：gaojiahui
Time：2025/8/14 20:41
Website：https://gitee.com/gao-jiahui
"""
import base64
import time

from day02_token.jwt_token import decode_token
from persistent_auth_manager import PersistentAuthManager

"""Token过期处理"""

class SmartAuthManager(PersistentAuthManager):
    def get_auth_headers(self):
        """智能处理Token过期"""
        if not self.token or self.is_token_expired():
            if not self.refresh_token:
                raise ValueError("需要重新登录")
            self.refresh_access_token()
        return super().get_auth_headers()

    def is_token_expired(self):
        """检查Token是否过期"""
        if not self.token:
            return True

        # 实际项目应从JWT解析exp时间
        # 这里简化为固定时间检查
        response = self.session.get(
            f"{self.base_url}/admin/user/info",
            headers={"Authorization":f"Bearer {self.token}"}
        )
        return response.status_code == 401

    def refresh_access_token(self):
        """刷新访问令牌"""
        url = f"{self.base_url}/auth/oauth/token"
        data = {
            "grant_type": "refresh_token",
            "refresh_token": self.refresh_token,
            "scope": "server"
        }

        auth_headers = {
            "Authorization": "Basic " + base64.b64encode(b"test:test").decode()
        }

        response = self.session.post(url,data=data,headers=auth_headers)

        if response.status_code == 200:
            token_data = response.json()
            self.token = token_data["access_token"]
            self.refresh_token = token_data["refresh_token"]
            self.save_cookies()
            return True

        print(f"令牌刷新失败:{response.text}")
        return False

    @staticmethod
    def token_usage_monitor(auth_manager):
        """监控Token使用情况"""
        token_data = decode_token(auth_manager.token)
        expires_at = token_data["exp"]
        remaining = expires_at - time.time()
        print(f"Token将在 {remaining//60} 分钟后过期")